import React, { Component } from 'react'
import { connect } from 'react-redux'
import FineUploaderS3 from 'fine-uploader-wrappers/s3'
import Gallery from 'react-fine-uploader'
import { global as globalDuck } from 'ducks'
import { FILE_SERVER_ADDRESS } from 'env'
import 'react-fine-uploader/gallery/gallery.css'

async function readFileWidthAndHeight(blob) {
  return new Promise((resolve, reject) => {
    const image = new Image()
    let url
    if (window.URL && window.URL.createObjectURL) {
      url = window.URL
    } else if (window.webkitURL && window.webkitURL.createObjectURL) {
      url = window.webkitURL
    } else {
      url = null
    }
    if (url) {
      image.onerror = () => {
        console.log('Cannot determine dimensions for image.  May be too large.', 'error')
        reject(new Error('error'))
      }
      image.onload = () => {
        resolve({ width: image.width, height: image.height })
      }
      image.src = url.createObjectURL(blob)
    } else {
      console.log('No createObjectURL function available to generate image URL!', 'error')
      reject(new Error('error'))
    }
  })
}

class Upload extends Component {
  state = {}

  componentDidMount() {
    const {
      actionNewDatasetItem, activeDatasetId, activeDataset, orgName, path,
    } = this.props
    const folderPath = path || ''

    const S3BucketURL = 'http://testimageupload.s3.cn-northwest-1.amazonaws.com.cn'
    const S3BucketAccessKey = 'AKIAPYVNV4DI64WUAG2A'
    const S3SigURL = 'http://52.82.21.90:8080/s3handler'
    const getFileSize = (id, uploader) => uploader.methods.getSize(id)
    const getUUID = (id, uploader) => uploader.methods.getUuid(id)
    const getFile = (id, uploader) => uploader.methods.getFile(id)
    let uploader
    uploader = new FineUploaderS3({
      options: {
        deleteFile: {
          enabled: false,
          endpoint: S3SigURL,
        },
        request: {
          endpoint: S3BucketURL,
          accessKey: S3BucketAccessKey,
        },
        signature: {
          endpoint: S3SigURL,
          version: 4,
        },
        objectProperties: {
          region: 'cn-northwest-1',
          bucket: 'testimageupload',
        },
        retry: {
          enableAuto: true,
        },
        callbacks: {
          async onComplete(id, name, responseJson) {
            if (responseJson && responseJson.success === true) {
              const size = getFileSize(id, uploader)
              const uuid = getUUID(id, uploader)
              const index = name.lastIndexOf('.')
              const suffix = name.substring(index + 1)
              const realName = `${uuid}.${suffix}`
              const file = getFile(id, uploader)
              const { width, height } = await readFileWidthAndHeight(file)
              const item = {
                datasetId: activeDatasetId,
                path: folderPath,
                name,
                realName,
                size,
                isFolder: false,
                metadata: {
                  width,
                  height,
                },
              }
              actionNewDatasetItem(item)
            }
          },
        },
      },
    })
    this.setState({ uploader })
  }

  render() {
    const { uploader } = this.state
    if (uploader) return <Gallery uploader={uploader} />
    return null
  }
}

const mapDispatchToProps = {
  actionNewDatasetItem: globalDuck.creators.actionNewDatasetItem,
}

export default connect(
  null,
  mapDispatchToProps,
)(Upload)
